package com.example.cv.controller;

import com.example.cv.model.ACEmployee;
import com.example.cv.model.Candidate;
import com.example.cv.model.Employee;
import com.example.cv.model.Employer;
import com.example.cv.service.EmployeeService;
import com.example.cv.util.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {
    public EmployeeService employeeService;

    @Autowired
    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @Autowired
    public JavaMailSenderImpl mailSender;

    /**
     * description:求职者投递简历（插入雇佣表）
     * @param c_id,e_id,model
     * @return
     */
    public void apply(int c_id, int e_id){
        Employee employee=employeeService.findEmployeesByIds(c_id,e_id);
        if(employee==null){
            boolean flag2=employeeService.addEmployee(c_id,e_id);
        }
    }

    /**
     * description:求职者在搜索页面投递简历
     * @param c_id,e_id,model
     * @return java.lang.String
     */
    @GetMapping("/searchApply")
    public String searchApply(int c_id, int e_id){
        apply(c_id,e_id);
        return "redirect:findAllEmployers?c_id="+c_id;
    }
    /**
     * description:求职者在内容推荐系统页面投递简历
     * @param c_id,e_id,model
     * @return java.lang.String
     */
    @GetMapping("/recommendApply")
    public String recommendApply(int c_id, int e_id){
        apply(c_id,e_id);
        return "redirect:candidateRecommend?c_id="+c_id;
    }
    /**
     * description:求职者查询所有求职消息
     * @param model_1,model_2
     * @return java.lang.String
     */
    @GetMapping("/candidateNotice")
    public String candidateNotice(int c_id, Model model_1, Model model_2, @RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "9") int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Employer> employers=employeeService.findEmployersInEmployeesByCId(c_id);
        //放入分页对象中,第二个参数表示最多连续显示的页数5
        PageInfo<Employer> pageInfo=new PageInfo<Employer>(employers,5);
        if(employers.isEmpty()){
            model_1.addAttribute("message","暂无通知！");
        }else{
            Map<Employer, Employee>employerEmployeeMap = new HashMap<Employer, Employee>();
            for (int i = 0; i < employers.size(); i++) {
                Employee employee=employeeService.findEmployeesByIds(c_id,employers.get(i).getE_id());
                employerEmployeeMap.put(employers.get(i),employee);
//            System.out.println("id="+employee.getId()+",c_id="+employee.getC_id()+",e_id="+employee.getE_id()+",cv_id="+employee.getCv_idAgree()+",interview_id="+employee.getInterview_idAgree());
            }
            model_1.addAttribute("employees",employers);
            model_2.addAttribute("employerEmployeeMap",employerEmployeeMap);
            model_2.addAttribute("pageInfo",pageInfo);
        }
        return "candidateNotice";
    }
    /**
     * description:用人单位处理简历消息（同意/不同意通用）
     * @param c_id
     * @return
     */
    public void informCV(int c_id,int e_id,int cv_isAgree){
        Employee employee=employeeService.findEmployeesByIds(c_id,e_id);
        if(employee==null){
            boolean flag1=employeeService.addEmployee(c_id,e_id);
        }
        boolean flag2=employeeService.informCV(c_id,e_id,cv_isAgree);
    }
    /**
     * description:用人单位处理面试消息（同意/不同意通用）
     * @param c_id
     * @return
     */
    public void informInterview(int c_id,int e_id,int interview_isAgree,Model model){
        boolean flag=employeeService.informInterview(c_id,e_id,interview_isAgree);
        if(flag){
            model.addAttribute("message","消息已发送！");
        }else{
            model.addAttribute("message","发送失败！请重试！");
        }
    }

    @GetMapping("/agreeRecommendCV")
    public String agreeRecommendCV(int c_id, int e_id, int cv_isAgree){
        informCV(c_id,e_id,cv_isAgree);
        return "redirect:employerRecommend?e_id="+e_id;
    }

    /**
     * description:用人单位在线选用应聘者（搜索页面）
     * @param c_id,e_id,cv_isAgree,model
     * @return java.lang.String
     */
    @GetMapping("/agreeCVLive")
    public String agreeCVLive(int c_id, int e_id, int cv_isAgree){
        informCV(c_id,e_id,cv_isAgree);
        return "redirect:findAllCandidates?e_id="+e_id;
    }
    /**
     * description:用人单位查询所有聘用消息
     * @param model_1,model_2
     * @return java.lang.String
     */
    @GetMapping("/employerNotice")
    public String employerNotice(int e_id, Model model_1, Model model_2, @RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "9") int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Candidate> candidates=employeeService.findCandidatesInEmployeesByEId(e_id);
        //放入分页对象中,第二个参数表示最多连续显示的页数5
        PageInfo<Candidate> pageInfo=new PageInfo<Candidate>(candidates,5);
        if(candidates.isEmpty()){
            model_1.addAttribute("message","暂无应聘者！");
        }else{
            Map<Candidate, Employee>candidateEmployeeMap = new HashMap<Candidate, Employee>();
            for (int i = 0; i < candidates.size(); i++) {
                Employee employee=employeeService.findEmployeesByIds(candidates.get(i).getC_id(),e_id);
                candidateEmployeeMap.put(candidates.get(i),employee);
//            System.out.println("id="+employee.getId()+",c_id="+employee.getC_id()+",e_id="+employee.getE_id()+",cv_id="+employee.getCv_idAgree()+",interview_id="+employee.getInterview_idAgree());
            }
            model_1.addAttribute("employees",candidates);
            model_2.addAttribute("candidateEmployeeMap",candidateEmployeeMap);
            model_2.addAttribute("pageInfo",pageInfo);
        }
        return "employerNotice";
    }
    /**
     * description:用人单位通过应聘者简历
     * @param c_id,e_id,cv_isAgree,model
     * @return java.lang.String
     */
    @GetMapping("/agreeCV")
    public String agreeCV(int c_id, int e_id, int cv_isAgree){
        informCV(c_id,e_id,cv_isAgree);
        return "redirect:employerNotice?e_id="+e_id;
    }
    /**
     * description:用人单位拒绝应聘者简历
     * @param c_id,e_id,cv_isAgree,model
     * @return java.lang.String
     */
    @GetMapping("/disagreeCV")
    public String disagreeCV(int c_id, int e_id, int cv_isAgree){
        informCV(c_id,e_id,cv_isAgree);
        return "redirect:employerNotice?e_id="+e_id;
    }
    /**
     * description:用人单位通过应聘者面试
     * @param c_id,e_id,cv_isAgree,model
     * @return java.lang.String
     */
    @GetMapping("/agreeInterview")
    public String agreeInterview(int c_id, int e_id, int interview_isAgree, Model model){
        informInterview(c_id,e_id,interview_isAgree,model);
        //同意之后，查询字段c_name,major,e_name插入tb_ac_employee表中
        boolean flag=employeeService.addACEmployeeByIds(c_id,e_id);
        return "redirect:employerNotice?e_id="+e_id;
    }
    /**
     * description:用人单位拒绝应聘者面试
     * @param c_id,e_id,cv_isAgree,model
     * @return java.lang.String
     */
    @GetMapping("/disagreeInterview")
    public String disagreeInterview(int c_id, int e_id, int interview_isAgree, Model model){
        informInterview(c_id,e_id,interview_isAgree,model);
        return "redirect:employerNotice?e_id="+e_id;
    }

    @GetMapping("/findAllAcceptedCandidatesByEId")
    public String findAllAcceptedCandidatesByEId(int e_id,Model model ,@RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "9") int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Candidate>candidates=employeeService.findAllAcceptedCandidatesByEId(e_id);
        //放入分页对象中,第二个参数表示最多连续显示的页数5
        PageInfo<Candidate> pageInfo=new PageInfo<Candidate>(candidates,5);
        model.addAttribute("candidates",candidates);
        model.addAttribute("pageInfo",pageInfo);
        return "employeesManage";
    }

    public void findAcceptedCandidatesByParams(String school,String e_name,Model model,@RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "9") int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<ACEmployee>acEmployees=employeeService.findAcceptedCandidatesByParams(school,e_name);
        //放入分页对象中,第二个参数表示最多连续显示的页数5
        PageInfo<ACEmployee> pageInfo=new PageInfo<ACEmployee>(acEmployees,5);
        model.addAttribute("acEmployees",acEmployees);
        model.addAttribute("school",school);
        model.addAttribute("pageInfo",pageInfo);
    }
    /**
     * description:Get用于分页
     * @param school, e_name, model, pageNum, pageSize
     * @return java.lang.String
     */
    @GetMapping("/findAcceptedCandidatesByParams")
    public String findAcceptedCandidatesByParamsGet(String school,String e_name,Model model,@RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "9") int pageSize) {
        findAcceptedCandidatesByParams(school,e_name,model,pageNum,pageSize);
        return "orderedEmployeesManage";
    }

    @PostMapping("/findAcceptedCandidatesByParams")
    public String findAcceptedCandidatesByParamsPost(String school,String e_name,Model model,@RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "9") int pageSize) {
        findAcceptedCandidatesByParams(school,e_name,model,pageNum,pageSize);
        return "orderedEmployeesManage";
    }

    /**
     * description:导入到Excel表格中
     * @param response
     * @return void
     */
    @GetMapping("/exportExcel")
    public void export(String school,String e_name,HttpServletResponse response){
        List<ACEmployee> acEmployees = employeeService.findAcceptedCandidatesByParams(school,e_name);
        //导出操作
        ExcelUtil.exportExcel(acEmployees,"聘用信息","sheet1",ACEmployee.class,"employees.xls",response);
    }
    /**
     * description:用人单位邮件发送
     * @param
     * @return java.lang.String
     */
    @GetMapping("/empSendEmail")
    public String empSendEmailGet(){
        return "employerEmailSending";
    }

    public void sendEmail(String to, String subject, String text, MultipartFile file, Model model) throws MessagingException, IOException {
        //创建一个Mime消息
        MimeMessage mimeMessage=mailSender.createMimeMessage();;
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
        //邮件主题
        helper.setSubject(subject);
        //邮件内容,true表示带有附件或html
        helper.setText(text,true);
//        添加附件内容
        //        采用file.Transto来保存上传的文件
        if (!file.isEmpty()){
            //       fileName: 文件名
            String fileName=file.getOriginalFilename();
//        filepath：文件保存的路径
            String filePath="C:\\Users\\周杰\\Desktop";
            File dest=new File(filePath+"/"+fileName);
            try {
                file.transferTo(dest);
//            return "email";
            } catch (Exception e) {
                e.printStackTrace();
            }
            //添加附件时要暂时将文件名为fileName的文件存到dest，然后再发送到邮箱
            helper.addAttachment(fileName,dest);
        }
        //发送给谁
        helper.setTo(to);
        //谁发邮件，要和配置文件写的一样
        helper.setFrom("2390262276@qq.com");
        mailSender.send(mimeMessage);
        model.addAttribute("msg","邮件发送成功");
    }

    @PostMapping("/empSendEmail")
    public String empSendEmailPost(String to, String subject, String text, MultipartFile file, Model model) throws MessagingException, IOException {
        sendEmail(to,subject,text,file,model);
        return "employerEmailSending";
    }

    /**
     * description:用人单位邮件发送
     * @param
     * @return java.lang.String
     */
    @GetMapping("/canSendEmail")
    public String canSendEmailGet(){
        return "candidateEmailSending";
    }

    @PostMapping("/canSendEmail")
    public String canSendEmailPost(String to, String subject, String text, MultipartFile file, Model model) throws MessagingException, IOException {
        sendEmail(to,subject,text,file,model);
        return "candidateEmailSending";
    }

}
